package com.momochen.alarmclockdemo.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.momochen.alarmclockdemo.AlarmAlertWakeLock;
import com.momochen.alarmclockdemo.AlarmConstant;
import com.momochen.alarmclockdemo.AlarmControl;
import com.momochen.alarmclockdemo.R;
import com.momochen.alarmclockdemo.activity.MainActivity;
import com.momochen.alarmclockdemo.bean.AlarmBean;
import com.momochen.alarmclockdemo.bean.DaysOfWeek;
import com.momochen.alarmclockdemo.service.AlarmKlaxonService;

import static com.momochen.alarmclockdemo.AlarmConstant.ALARM_RAW_DATA;

/**
 * Created by momochen on 2017/7/9.
 */

public class AlarmReceiver extends BroadcastReceiver {

    /**
     * If the alarm is older than STALE_WINDOW, ignore.  It
     * is probably the result of a time or timezone change
     */
    private final static int STALE_WINDOW = 30 * 60 * 1000;

    @Override
    public void onReceive(Context context, Intent intent) {
//        AlarmBean alarmBean = (AlarmBean) intent.getSerializableExtra(ALARM_RAW_DATA);
        if (AlarmConstant.ALARM_KILLED.equals(intent.getAction())) {
            // The alarm has been killed, update the notification
            updateNotification(context, (AlarmBean) intent.getSerializableExtra(AlarmConstant.ALARM_INTENT_EXTRA), intent.getIntExtra(AlarmConstant.ALARM_KILLED_TIMEOUT, -1));
            return;
        } else if (AlarmConstant.CANCEL_SNOOZE.equals(intent.getAction())) {
            AlarmControl.saveSnoozeAlert(context, -1, -1);
            return;
        } else if (!AlarmConstant.ALARM_ALERT_ACTION.equals(intent.getAction())) {
            return;
        }

        Bundle bundle = intent.getBundleExtra("BUNDLE");
        if (bundle == null) {
            AlarmControl.setNextAlert(context);
            return;
        }

        AlarmBean alarmBean = (AlarmBean) bundle.getSerializable(ALARM_RAW_DATA);
        System.out.println("====onReceive>" + (alarmBean == null));
        if (alarmBean == null || alarmBean.getId() == null) {
            AlarmControl.setNextAlert(context);
            return;
        }
        // Disable the snooze alert if this alarm is the snooze.
        AlarmControl.disableSnoozeAlert(context, alarmBean.getId());

        // Disable this alarm if it does not repeat.
        if (!new DaysOfWeek(alarmBean.getDaysOfWeek()).isRepeatSet()) {
            AlarmControl.enableAlarm(context, alarmBean.getId(), false);
        } else {
            // Enable the next alert if there is one. The above call to
            // enableAlarm will call setNextAlert so avoid calling it twice.
            AlarmControl.setNextAlert(context);
        }

        // Intentionally verbose: always log the alarm time to provide useful
        // information in bug reports.
        long now = System.currentTimeMillis();

        // Always verbose to track down time change problems.
        if (now > alarmBean.getTimeStamp() + STALE_WINDOW) {
            return;
        }

        // Maintain a cpu wake lock until the AlarmAlert and AlarmKlaxon can
        // pick it up.
        AlarmAlertWakeLock.acquireCpuWakeLock(context);

        /* Close dialogs and window shade */
        Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.sendBroadcast(closeDialogs);

        Intent playAlarm = new Intent(context, AlarmKlaxonService.class);
        playAlarm.putExtra(AlarmConstant.ALARM_INTENT_EXTRA, alarmBean);
        context.startService(playAlarm);

//        Intent notify = new Intent(context, AlarmAlert.class);
//        notify.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm);
//        PendingIntent pendingNotify = PendingIntent.getActivity(context,
//                (int) (long) alarmBean.getId(), notify, 0);

        Notification notification = new Notification.Builder(context)
                .setOngoing(true)
                .setContentTitle("闹钟")
                .setContentText(context.getString(R.string.alarm_notify_text))
//                .setContentIntent(pendingNotify)
//                .setDeleteIntent(pendingNotify)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(alarmBean.getTimeStamp())
                .build();

        // NEW: Embed the full-screen UI here. The notification manager will
        // take care of displaying it if it's OK to do so.
//        Intent alarmAlert = new Intent(context, c);
//        alarmAlert.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm);
//        alarmAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
//        notification.fullScreenIntent = PendingIntent.getActivity(context, (int) alarmBean.getId(), alarmAlert, 0);

        // Send the notification using the alarm id to easily identify the
        // correct notification.
        NotificationManager nm = getNotificationManager(context);
        nm.notify((int) (long) alarmBean.getId(), notification);
    }

    private NotificationManager getNotificationManager(Context context) {
        return (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    private void updateNotification(Context context, AlarmBean alarm, int timeout) {
        NotificationManager nm = getNotificationManager(context);

        // If the alarm is null, just cancel the notification.
        if (alarm == null || alarm.getId() == null) {
            return;
        }

        int id = (int) (long) alarm.getId();

        // Launch SetAlarm1 when clicked.
        Intent viewAlarm = new Intent(context, MainActivity.class);
        viewAlarm.putExtra(AlarmConstant.ALARM_ID, alarm.getId());
        PendingIntent intent = PendingIntent.getActivity(context, id, viewAlarm, 0);

        Notification notification = new Notification.Builder(context)
                .setAutoCancel(true)
                .setContentTitle(context.getString(R.string.alarm_notify_text))
                .setContentText("闹钟响铃时间为" + timeout + "分钟")
                .setContentIntent(intent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(alarm.getTimeStamp())
                .build();

//        Notification n = new Notification(R.drawable.stat_notify_alarm,
//                label, alarm.time);
//        n.setLatestEventInfo(context, label,
//                context.getString(R.string.alarm_alert_alert_silenced, timeout),
//                intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;


        // We have to cancel the original notification since it is in the
        // ongoing section and we want the "killed" notification to be a plain
        // notification.
        nm.cancel(id);
        nm.notify(id, notification);
    }
}
